package grapid.util;

import javax.servlet.http.HttpServletRequest;

/**
 * IP查找类
 * 
 * @author grapid
 * @version 2.0
 * 
 */
public class GIP {

	/**
	 * 选项
	 */
	public static String IPOption = "X-Real-IP,x-forwarded-for,Proxy-Client-IP,WL-Proxy-Client-IP";

	/**
	 * 取访问者IP
	 * 
	 * @param request
	 * @return 返回ip
	 */
	public static String getIP(HttpServletRequest request) {
		String ip = null;
		for (String ipo : IPOption.split(",")) {
			if (ip == null || "".equals(ip) || "unknown".equalsIgnoreCase(ip))
				ip = request.getHeader(ipo);
			else
				break;
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
			ip = request.getRemoteAddr();
		if (ip != null) {
			ip = ip.replaceAll("(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}),?.*", "$1");
			if (ip.length() > 15)
				ip = ip.substring(0, 15);
		}
		return ip;
	}

	/**
	 * IP转化为数值型
	 * 
	 * @param ip
	 *            待转换IP
	 * @return 返回Long型值
	 */
	public static long ipToInt(String ip) {
		String[] ips = ip.split(",");
		long nip = 0;
		if (ips.length >= 4)
			nip = Integer.parseInt(ips[0]) * 256 * 256 * 256 + Integer.parseInt(ips[1]) * 256 * 256
					+ Integer.parseInt(ips[2]) * 256 + Integer.parseInt(ips[3]);
		return nip;
	}

	/**
	 * 比较IP范围
	 * 
	 * @param startIp
	 *            起始IP
	 * @param endIp
	 *            截止IP
	 * @param ip
	 *            待查询IP
	 * @return 返回是否包含在范围内
	 */
	public static boolean isIn(String startIp, String endIp, String ip) {
		long nip = ipToInt(ip);
		return nip >= ipToInt(startIp) && nip <= ipToInt(endIp);
	}
}
